package com.googlecode.continuity.plugin.rating.server.rpc;

import org.acegisecurity.context.SecurityContextHolder;
import com.googlecode.continuity.core.server.security.SecurityUserToken;
import com.googlecode.continuity.plugin.rating.client.RatingInfo;
import com.googlecode.continuity.plugin.rating.client.RatingRPC;
import com.googlecode.continuity.plugin.rating.server.service.RatingService;

/**
 * RatingRPCImpl
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class RatingRPCImpl implements RatingRPC {
  private RatingService ratingService;

  // todo: do not allow unauthenticated access
  // todo: do not allow self-ratings
  public RatingInfo setRating(int messageId, int rating) {
    ratingService.setRating(
        ((SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser().getId(),
        messageId, rating);

    RatingInfo info = new RatingInfo();
    info.setCurrentUserRating(rating);
    info.setRatingCount(ratingService.getRatingCount(messageId));
    info.setAverage(ratingService.getRatingAverage(messageId));
    return info;
  }

  public RatingInfo getRating(int messageId) {
    RatingInfo info = new RatingInfo();
    SecurityUserToken userToken =
        (SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (userToken != null && userToken instanceof SecurityUserToken) {
      info.setCurrentUserRating(ratingService.getRating(userToken.getUser().getId(), messageId));
    }
    info.setRatingCount(ratingService.getRatingCount(messageId));
    info.setAverage(ratingService.getRatingAverage(messageId));
    return info;
  }

  public void setRatingService(RatingService ratingService) {
    this.ratingService = ratingService;
  }
}
